package com.winning.pmph.interceptor;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;
import java.util.stream.Stream;

@Component
public class KmsCacheInterceptor implements HandlerInterceptor {

    public static String cacheId = IdWorker.getIdStr();

    public static String refreshCacheId() {
        cacheId = IdWorker.getIdStr();
        return cacheId;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (checkAndSetCacheId(request, response)) {
            return true;
        }
        if (request.getRequestURI().contains("select")) {
            return true;
        }
        throw new RuntimeException("缓存已更新, 请重新操作");
    }

    private boolean checkAndSetCacheId(HttpServletRequest request, HttpServletResponse response) {
        Optional<Cookie> optionalCookie = Stream.of(request.getCookies())
                .filter(cookie -> StringUtils.equals("cacheId", cookie.getName()))
                .findFirst();
        if (optionalCookie.isPresent() && StringUtils.equals(this.cacheId, optionalCookie.get().getValue())) {
            return true;
        }
        Cookie cacheIdCookie = new Cookie("cacheId", cacheId);
        cacheIdCookie.setPath("/");
        response.addCookie(cacheIdCookie);
        return false;
    }
}
